package me.goldze.mvvmhabit.http.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

public class ProgressRequestBody extends RequestBody {
    private File file;
    private ProgressCallback progressCallback;

    public ProgressRequestBody(File file, ProgressCallback progressCallback) {
        this.file = file;
        this.progressCallback = progressCallback;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("multipart/form-data");
    }

    @Override
    public long contentLength() {
        return file.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        long fileLength = file.length();
        long uploadedBytes = 0;

        try (InputStream inputStream = new FileInputStream(file)) {
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                sink.write(buffer, 0, read);
                uploadedBytes += read;
                int progress = (int) (uploadedBytes * 100 / fileLength);
                progressCallback.onProgress(progress, (int) fileLength);
            }
        }
    }

    private static final int DEFAULT_BUFFER_SIZE = 2048;
}
